package com.nodecollege.cloud.common.model.vo;

import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.model.po.UpmsOrg;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 组织机构树
 *
 * @author LC
 * @date 2019/12/11 18:08
 */
@Data
public class OrgTreeVO extends UpmsOrg implements Comparable<OrgTreeVO> {
    /**
     * 子集
     */
    private List<OrgTreeVO> children;

    public OrgTreeVO() {
    }

    public OrgTreeVO(UpmsOrg org) {
        super.setOrgId(org.getOrgId());
        super.setOrgCode(org.getOrgCode());
        super.setOrgName(org.getOrgName());
        super.setOrgType(org.getOrgType());
        super.setParentId(org.getParentId());
        super.setState(org.getState());
        super.setNum(org.getNum());
        super.setTenantId(org.getTenantId());
    }

    public static List<OrgTreeVO> getOrgTree(List<UpmsOrg> orgList) {
        return getOrgTree(orgList, 0L);
    }

    /**
     * 获取menuTree
     *
     * @return
     */
    public static List<OrgTreeVO> getOrgTree(List<UpmsOrg> orgList, Long pid) {
        List<OrgTreeVO> orgTreeList = new ArrayList<>();
        Iterator<UpmsOrg> orgIterator = orgList.iterator();
        while (orgIterator.hasNext()) {
            UpmsOrg org = orgIterator.next();
            if (org.getParentId().equals(pid)) {
                orgTreeList.add(new OrgTreeVO(org));
                orgIterator.remove();
            }
        }
        Collections.sort(orgTreeList);
        for (OrgTreeVO orgTreeVO : orgTreeList) {
            orgTreeVO.setChildren(getOrgTree(orgList, orgTreeVO.getOrgId()));
        }
        if (orgTreeList.isEmpty()){
            return null;
        }
        return orgTreeList;
    }

    @Override
    public int compareTo(OrgTreeVO o) {
        return this.getNum().compareTo(o.getNum());
    }
}
